package com.zhiyin.seal.task;

import com.alibaba.fastjson.JSONObject;
import com.zhiyin.seal.entity.bo.AccessTokenBo;
import com.zhiyin.seal.entity.bo.ApplyNotesBo;
import com.zhiyin.seal.service.ApplyService;
import com.zhiyin.seal.service.SystemService;
import com.zhiyin.seal.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class WxMiniprogramTask {

    private static String ACCESS_TOKEN = null;

    private static final String APP_ID = "wx7891e790f3284cd7";
    private static final String SECRET = "3698439b21019903b3765fc31659ce4a";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

    public static final SimpleDateFormat DATETIME_FORMATE = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    @Autowired
    SystemService systemService;

    @Autowired
    ApplyService applyService;

    @Scheduled(fixedDelay = 1000 * 60 * 60)
    public void getAccessToken(){
        // 向微信服务器获取token
        String result = HttpUtil.doGet(String.format(ACCESS_TOKEN_URL,APP_ID,SECRET));
        if(result == null)
            return;
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String accessToken = jsonObject.getString("access_token");
            if(accessToken != null){
                ACCESS_TOKEN = accessToken;

                AccessTokenBo accessTokenBo = new AccessTokenBo();
                accessTokenBo.setType(1);
                accessTokenBo.setAppId(APP_ID);
                accessTokenBo.setSecret(SECRET);
                accessTokenBo.setToken(accessToken);

                systemService.updateAccessToken(accessTokenBo);
            }
        } catch (Exception ex){
            System.out.println("获取token异常:" + ex.toString());
        }
    }

    @Scheduled(fixedDelay = 1000 * 10)
    public void sendApprovalResult(){
        if(ACCESS_TOKEN == null){
            AccessTokenBo accessTokenBo = systemService.getAccessToken(1);
            if(accessTokenBo == null){
                getAccessToken();
                return;
            } else {
                ACCESS_TOKEN = accessTokenBo.getToken();
            }
        }

        // 获取申请单据审批状态
        List<ApplyNotesBo> applyNotesBoList = applyService.getApplyNotesList();
        if(applyNotesBoList.size() == 0){
            return;
        }
        // 更新通知状态
        List<Long> idList = applyNotesBoList.stream().map(ApplyNotesBo::getId).collect(Collectors.toList());
        if(idList.size() > 0){
            applyService.updateApplyNotes(idList);
        }
        for(ApplyNotesBo applyNotesBo : applyNotesBoList){
            String jsonString = null;
            String reason = applyNotesBo.getReason();
            String nickName = applyNotesBo.getNickName();
            String opinion = applyNotesBo.getOpinion();
            if(reason.length() > 20){
                reason = reason.substring(0,15) + "...";
            }
            if(nickName.length() > 20){
                nickName = nickName.substring(0,15) + "...";
            }
            if(opinion.length() > 20){
                opinion = opinion.substring(0,15) + "...";
            }
            // 审批通过
            if(applyNotesBo.getApprovalStatus().equals(2)){
                jsonString = "{\n" +
                        "  \"access_token\": \"%s\",\n" +
                        "  \"touser\": \"%s\",\n" +
                        "  \"template_id\": \"%s\",\n" +
                        "  \"page\": \"pages/tabbar/home/index\",\n" +
                        "  \"data\": {\n" +
                        "      \"thing1\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"thing2\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"thing5\": {\n" +
                        "          \"value\": \"用印申请\"\n" +
                        "      },\n" +
                        "      \"time3\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"time4\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      }\n" +
                        "  }\n" +
                        "}";
                jsonString = String.format(jsonString,ACCESS_TOKEN,applyNotesBo.getOpenId(),"PhmLACtYXZlbGn2aUwcIPzpuuhygVupQvVlUQz0BSko",
                        reason,nickName,
                        DATETIME_FORMATE.format(applyNotesBo.getApplyTime()),
                        DATETIME_FORMATE.format(applyNotesBo.getCreateTime()));
            }
            // 驳回
            else if(applyNotesBo.getApprovalStatus().equals(3)) {
                jsonString = "{\n" +
                        "  \"touser\": \"%s\",\n" +
                        "  \"template_id\": \"%s\",\n" +
                        "  \"page\": \"pages/tabbar/home/index\",\n" +
                        "  \"data\": {\n" +
                        "      \"thing1\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"thing4\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"thing3\": {\n" +
                        "          \"value\": \"用印申请\"\n" +
                        "      },\n" +
                        "      \"time2\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      },\n" +
                        "      \"thing5\": {\n" +
                        "          \"value\": \"%s\"\n" +
                        "      }\n" +
                        "  }\n" +
                        "}";
                jsonString = String.format(jsonString,applyNotesBo.getOpenId(),"WTQYgj76ljMyEHDv_KAAQqlj69zDtKWW68lmKWZ1oy0",
                        reason,nickName,
                        DATETIME_FORMATE.format(applyNotesBo.getCreateTime()),
                        opinion);
            }

            if(jsonString != null){
                // 推送到微信
                HttpUtil.doPostJSON(String.format(SEND_URL,ACCESS_TOKEN),jsonString);
            }
        }
    }
}
